package com.mj.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mj.dao.system.MenuMapper;
import com.mj.dao.system.RoleMapper;
import com.mj.model.system.Menu;
import com.mj.model.system.Role;
import com.mj.util.CommonUtil;
import com.mj.util.PasswordHelper;

@Service("menuService")
public class MenuServiceImpl implements MenuService {

	@Resource
	private MenuMapper menuDao;
	@Resource
	private RoleMapper roleDao;
	@Resource
    private PasswordHelper passwordHelper;
	@Resource
    CommonUtil commonUtil;
	@Override
	public Menu selectById(Integer menuId) {
		return this.menuDao.selectByPrimaryKey(menuId);
	}
	@Override
	public List<Menu> getMenuList(Integer pid) {
		return menuDao.getAllMenuByPId(pid);
	}
	@Override
	public List<Menu> getMenuByIdList(String []ids,String menuName) {
		return menuDao.getAllMenuById(ids,menuName);
	}
	@Override
	public int updateMenu(Menu menu) {
		return menuDao.updateMenu(menu);
	}
	@Override
	public int insertMenu(Menu menu) {
		menu.setAvailable(0);
		menu.setIsDefault(0);
		menu.setParentMenuIds(menu.getParentMenuIds()+ menu.getParentMenuId() + "-");
		return menuDao.insertMenu(menu);
	}
	@Override
	public int deleteByMenuId(Integer id) {
		return menuDao.deleteByMenuId(id);
	}
	@Override
	public int updateByMenuId(Integer menuId,Integer available) {
		return menuDao.updateByMenuId(menuId,available);
	}
	@Override
	public List<Menu> findAll(Map<String,Object> map) {
		return menuDao.findAllMenu(map);
	}
	
	@Override
	public Set<String> findPermissions(String resourceIds) {
		Set<String> permissions = new HashSet<String>();
		if(!resourceIds.equals("") && resourceIds!=null){
			String[] bids = resourceIds.split(",");
	        for(String resourceId : bids) {
                permissions.add(resourceId);
	        }
		}
	    return permissions;
	}
	@Override
	public Set<String> getMenusByPermisson(int roleid) {
		 Role role = roleDao.selectByPrimaryKey(roleid);
        // 获取当前用户的角色id
        String roleIds[] = role.getMenuIds().split(",");
        // 用来存储menuid对应的parentMenuIds
        String flag = "";
        // set筛选不重复数据
        Set<String> hSet = new HashSet<String>();
        for (String s : roleIds){
            // 查找当前角色id的相关信息
            Menu ms = menuDao.selectByPrimaryKey(Integer.parseInt(s));
            // 可能存在菜单被删除的情况
            if (null != ms){
                flag += ms.getParentMenuIds();
                // 同时添加角色id
                hSet.add(s);
            }else{
                String menuIds = role.getMenuIds();
                // 判断字符串出现位置，1, || ,1
                String new_mIds =
                    menuIds.contains(s + ",") == true ? menuIds.replace(s + ",", "") : menuIds.replace("," + s, "");
                Role new_role = new Role();
                new_role.setRoleId(role.getRoleId());
                new_role.setMenuIds(new_mIds);
                // 修改全新menuIds
                roleDao.updateByPrimaryKeySelective(new_role);
            }
        }
        String flag_id[] = flag.split("-");
        // 将parentMenuIds和menuid组装进set集合中
        for (String sf : flag_id){
            hSet.add(sf);
        }
		return hSet;
	}
	@Override
	public String CUDMenu(String oper, String idarrs, Menu menu) {
		boolean success = false;
		JSONObject jsonObject = new JSONObject();
		int mid_new = 0;
		if(StringUtils.isNotEmpty(oper)){
			if(oper.equals("addORedit")){//修改、新增操作，id不为空=修改
				if(menu.getMenuId()!=0){
					menuDao.updateMenu(menu);
					success = true;
					oper = "edit";
				}else{
					int mid = menu.getParentMenuId();
					Menu cmenu = new Menu();
					cmenu.setMenuId(mid);
					menuDao.updateMenu(cmenu);
					//父节点parentMenuids+menuid
					menu.setParentMenuIds(menu.getParentMenuIds()+ menu.getParentMenuId() + "-");
					menu.setAvailable(0);
					menuDao.insertMenu(menu);
					success = true;
					oper = "add";
					mid_new = menu.getMenuId();
				}
			}
			if(oper.equals("del")){
				String[] ids = idarrs.split(",");
				for(String id:ids){
//					menuService.deleteByMenuId(Integer.parseInt(id));
					//删除只更改状态
					Menu m = new Menu();
					m.setAvailable(1);
					m.setMenuId(Integer.parseInt(id));
					menuDao.updateMenu(m);
				}
				success = true;
			}
		}
		 jsonObject.put("oper",oper);
		 jsonObject.put("success",success);
		 jsonObject.put("mid_new",mid_new);
		 jsonObject.put("menu", menu);
		 return jsonObject.toString();
	}
	@Override
	public List<Map<String, Object>> loadByMenuName(List<Menu> mlist,
			String name) {
		List<Map<String,Object>> maplist = null;
    	if(null != name && !name.equals("")){
    		maplist = new  ArrayList<Map<String,Object>>();  
    	    for (Menu m : mlist) {
 	    	   Map<String,Object> tn = new HashMap<String,Object>();
 	    	   tn.put("title", m.getMenuName());
 	    	   tn.put("href",m.getMenuUrl());
 	    	   tn.put("id",new Long(m.getMenuId()).intValue());
 	    	   tn.put("pid", m.getParentMenuId());
 	    	   tn.put("pids", m.getParentMenuIds());
 	    	   tn.put("icon",m.getIconUrl());
 	    	   tn.put("permission",m.getPermission());
 	    	  maplist.add(tn);
 	       }
    	}else{
    		maplist = commonUtil.treeMapList(mlist, 0);
    	}
		return maplist;
	}
	@Override
	public List<Menu> findAllMenuButtons() {
		return menuDao.findAllMenuButtons();
	}
	
	
}
